package com.zondy.mapgis.android.frag;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.zondy.mapgis.android.activity.MapActivity;
import com.zondy.mapgis.android.base.BaseFragment;
import com.zondy.mapgis.android.graphic.Graphic;
import com.zondy.mapgis.android.mapview.MapView;
import com.zondy.mapgis.android.model.EnumViewPos;
import com.zondy.mapgis.android.utils.MapUtil;
import com.zondy.mapgis.android.utils.SearchUtils;
import com.zondy.mapgis.android.utils.SearchUtils.MapSearchAnnotationListen;
import com.zondy.mapgis.android.view.Panel;
import com.zondy.mapgis.android.view.pulltorefresh.PullToRefreshLayout;
import com.zondy.mapgis.android.view.pulltorefresh.PullToRefreshLayout.OnRefreshListener;
import com.zondy.mapgis.core.attr.Field;
import com.zondy.mapgis.core.attr.Fields;
import com.zondy.mapgis.core.attr.Record;
import com.zondy.mapgis.core.featureservice.Feature;
import com.zondy.mapgis.core.featureservice.FeaturePagedResult;
import com.zondy.mapgis.core.geometry.Dot;
import com.zondy.mapgis.core.geometry.Rect;
import com.zondy.mapgis.explorer.MapApplication;
import com.zondy.mapgis.explorer.R;

public class SearchResultFrag extends BaseFragment implements OnClickListener
{

	private String TAG = this.getClass().getSimpleName();
	private MapActivity mMapActivity = null;
	private MapView mMapView = null;
	private FeaturePagedResult mFeaturePageResult = null;
	public MapSearchAnnotationListen SearchAnnotationListen = new MapSearchAnnotationListen();
	private List<Graphic> mGraphicLst = new ArrayList<Graphic>();

	private Panel mPanel = null;
	private LinearLayout mListContent = null;
	/** 结果展示列表ListView **/
	private ListView mPullListView = null;
	private TextView mSearchCountTv = null;
	private TextView mTitleTxt = null;
	private SearchResultAdapter mSearchResultAdapter = null;

	private final int[] mLocationIco = { R.drawable.ico_result_location_1, R.drawable.ico_result_location_2, R.drawable.ico_result_location_3, R.drawable.ico_result_location_4,
			R.drawable.ico_result_location_5, R.drawable.ico_result_location_6, R.drawable.ico_result_location_7, R.drawable.ico_result_location_8, R.drawable.ico_result_location_9,
			R.drawable.ico_result_location_10, R.drawable.ico_result_location_11, R.drawable.ico_result_location_22, R.drawable.ico_result_location_33, R.drawable.ico_result_location_44,
			R.drawable.ico_result_location_55, R.drawable.ico_result_location_66, R.drawable.ico_result_location_77, R.drawable.ico_result_location_88, R.drawable.ico_result_location_99,
			R.drawable.ico_result_location_100 };

	// 当前页数
	private int mCurPageIndex = 1;
	//要素的矩形外包
	private List<Rect> mRectLst = new ArrayList<Rect>();

	@Override
	public int bindLayout()
	{
		return R.layout.bottom_searchresult_view;
	}

	@Override
	public void initView(View view)
	{
		mPanel = (Panel) view.findViewById(R.id.result_bottompanel);
		mListContent = (LinearLayout) view.findViewById(R.id.list_content);
		mPullListView = (ListView) view.findViewById(R.id.search_result_lst);
		mSearchCountTv = (TextView) view.findViewById(R.id.search_count_tv);
		mTitleTxt = (TextView) view.findViewById(R.id.title_text);
		mTitleTxt.setText("查询结果");

		view.findViewById(R.id.title_back).setOnClickListener(this);
		mSearchCountTv.setOnClickListener(this);
		((PullToRefreshLayout) view.findViewById(R.id.refresh_view)).setOnRefreshListener(new ResultRefreshListen());

		Bundle data = getArguments();
		mFeaturePageResult = (FeaturePagedResult) data.get("FeaturePagedResult");

		mPanel.setOpen(true, true);
	}

	@Override
	public void doBusiness(Context mContext)
	{
		mMapActivity = MapApplication.getApp().getMapActivity();
		mMapView = mMapActivity.mMapView;
//		mMapActivity.mMapBottomContent.setVisibility(View.GONE);
//		mMapView.setAnnotationListener(SearchAnnotationListen);
		// 查询结果
		int totalCount = mFeaturePageResult.getTotalFeatureCount();
		mSearchCountTv.setText(totalCount + "条结果");

		mSearchResultAdapter = new SearchResultAdapter(getContext());
		mPullListView.setAdapter(mSearchResultAdapter);
		loadPageData(mCurPageIndex);
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.title_back:
			mMapActivity.removeFragment(TAG, null);
			break;
		case R.id.search_count_tv:
			if (mListContent.getLayoutParams().height == LinearLayout.LayoutParams.MATCH_PARENT)
			{
				LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 320);
				mListContent.setLayoutParams(params);
			}
			else
			{
				LinearLayout.LayoutParams pa = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
				mListContent.setLayoutParams(pa);
			}
			break;

		default:
			break;
		}

	}

	/**
	 * 加载一页数据
	 * 
	 * @param pageNum
	 */
	public List<Feature> loadPageData(int pageNum)
	{
		mMapView.getGraphicsOverlay().removeGraphics(mGraphicLst);
		mMapView.getAnnotationsOverlay().removeAllAnnotations();
		mRectLst.clear();
		mGraphicLst.clear();
		List<Feature> featureList = new ArrayList<Feature>();
		featureList = mFeaturePageResult.getPage(pageNum);
		
		mSearchResultAdapter.setFeatueLst(featureList);
		mSearchResultAdapter.notifyDataSetChanged();
		
		for (int k = 0; k < featureList.size(); k++)
		{
			Feature feature = featureList.get(k);
			List<Graphic> graphics = feature.toGraphics(true);
			for(Graphic gra:graphics)
			{
				//添加要素的方式一
				Log.d(TAG, "Graphic:"+gra);
				gra.setColor(Color.argb(50, 255, 0, 0));
				Dot curDot = gra.getCenterPoint();
//				SearchUtils.drawGraphicImageOnMap(getContext(), mMapView, mLocationIco[k], curDot);
				mMapView.getGraphicsOverlay().addGraphic(gra);
				//添加要素的方式二
				SearchUtils.addAnnotation(getContext(), mMapView, ""+k, null, null, curDot.x, curDot.y, mLocationIco[k], k);
				
				mGraphicLst.add(gra);
				mRectLst.add(gra.getBoundingRect());
			}
			mMapView.refresh();
			
			//测试代码
			Log.d(TAG, "graphics.size():"+graphics.size());
			// 获取要素属性
			Record record = feature.getAtt();
			// 获取要素字段结构
			Fields fields = feature.getFields();
			// 获取字段数目
			short fieldCount = fields.getFieldCount();
			for (short j = 0; j < fieldCount; j++)
			{
				Field field = fields.getField(j);
				// 获取字段名称
				String strFieldName = field.getFieldName();
				// 获取对应字段的值
				Object fieldValue = record.getFldVal(strFieldName);
//				Log.d(TAG, "strFieldName---" + k + ":" + strFieldName);
//				Log.d(TAG, "fieldValue===" + k + ":" + fieldValue);
			}
		}
		
		SearchUtils.zoomToGraphicsRect(getContext(), mMapView, mRectLst);
		graphicToCenter(0);
		return featureList;

	}

	/**
	 * 刷新监听
	 * 
	 * @author fjl
	 * 
	 */
	class ResultRefreshListen implements OnRefreshListener
	{

		@Override
		public void onRefresh(PullToRefreshLayout pullToRefreshLayout)
		{
			if (mCurPageIndex > 1)
			{
				mCurPageIndex--;
				loadPageData(mCurPageIndex);
				pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
			}
			else
			{
				pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
			}
		}

		@Override
		public void onLoadMore(PullToRefreshLayout pullToRefreshLayout)
		{
			if (mCurPageIndex < mFeaturePageResult.getPageCount())
			{
				mCurPageIndex++;
				loadPageData(mCurPageIndex);
				pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
			}
			else
			{
				pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
			}
		}

	}

	class SearchResultAdapter extends BaseAdapter
	{
		private Context context;
		private LayoutInflater inflater = null;
		private List<Feature> featureLst = new ArrayList<Feature>();

		public SearchResultAdapter(Context context)
		{
			this.context = context;
			this.inflater = LayoutInflater.from(this.context);
		}

		@Override
		public int getCount()
		{
			if (null == featureLst)
			{
				return 0;
			}
			else
			{
				return featureLst.size();
			}
		}

		@Override
		public Object getItem(int position)
		{
			if (null == featureLst)
			{
				return null;
			}
			else
			{
				return featureLst.get(position);
			}

		}

		@Override
		public long getItemId(int position)
		{
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent)
		{
			ViewHolder holder = null;

			if (null == convertView)
			{
				holder = new ViewHolder();
				convertView = inflater.inflate(R.layout.searchresult_list_item, null);
				holder.contentLayout = (LinearLayout) convertView.findViewById(R.id.content_layout);
				holder.idText = (TextView) convertView.findViewById(R.id.id_tv);
				holder.oidText = (TextView) convertView.findViewById(R.id.oid_tv);
				holder.nameOneText = (TextView) convertView.findViewById(R.id.fieldname_one_tv);
				holder.nameTwoText = (TextView) convertView.findViewById(R.id.fieldname_two_tv);
				holder.nameThreeText = (TextView) convertView.findViewById(R.id.fieldname_three_tv);
				holder.valueOneText = (TextView) convertView.findViewById(R.id.fieldvalue_one_tv);
				holder.valueTwoText = (TextView) convertView.findViewById(R.id.fieldvalue_two_tv);
				holder.valueThreeText = (TextView) convertView.findViewById(R.id.fieldvalue_three_tv);
				holder.featureDetailImv = (ImageView) convertView.findViewById(R.id.feature_detail_imv);
				holder.featureDetailLayout = (LinearLayout) convertView.findViewById(R.id.feature_detail_layout);

				convertView.setTag(holder);
			}
			else
			{
				holder = (ViewHolder) convertView.getTag();
			}

			final Feature feature = featureLst.get(position);
			holder.idText.setText(position + 1+":");
			holder.oidText.setText("OID = " + feature.getID());
			// 获取要素属性
			Record record = feature.getAtt();
			// 获取要素字段结构
			Fields fields = feature.getFields();
			// 获取字段数目
			short fieldCount = fields.getFieldCount();
			// 当要素的数目大于3的时候
			if (fieldCount > 3)
			{
				for (short j = 0; j < fieldCount; j++)
				{
					Field field = fields.getField(j);
					if (j == 0)
					{
						// 获取字段名称
						String strFieldName1 = field.getFieldName();
						// 获取对应字段的值
						Object fieldValue1 = record.getFldVal(strFieldName1);
						holder.nameOneText.setText(strFieldName1 + "");
						holder.valueOneText.setText(fieldValue1 + "");
					}
					if (j == 1)
					{
						// 获取字段名称
						String strFieldName2 = field.getFieldName();
						// 获取对应字段的值
						Object fieldValue2 = record.getFldVal(strFieldName2);
						holder.nameTwoText.setText(strFieldName2 + "");
						holder.valueTwoText.setText(fieldValue2 + "");
					}
					if (j == 2)
					{
						// 获取字段名称
						String strFieldName3 = field.getFieldName();
						// 获取对应字段的值
						Object fieldValue3 = record.getFldVal(strFieldName3);
						holder.nameThreeText.setText(strFieldName3 + "");
						holder.valueThreeText.setText(fieldValue3 + "");
					}

				}

			}
			// 当要素的数目小于3的时候
			if (fieldCount <= 3)
			{
				holder.featureDetailImv.setVisibility(View.GONE);
				for (short i = 0; i < fieldCount; i++)
				{
					Field field = fields.getField(i);
					if (i == 0)
					{
						// 获取字段名称
						String strFieldName1 = field.getFieldName();
						// 获取对应字段的值
						Object fieldValue1 = record.getFldVal(strFieldName1);
						holder.nameOneText.setText(strFieldName1 + "");
						holder.valueOneText.setText(fieldValue1 + "");
					}
					if (i == 1)
					{
						// 获取字段名称
						String strFieldName2 = field.getFieldName();
						// 获取对应字段的值
						Object fieldValue2 = record.getFldVal(strFieldName2);
						holder.nameTwoText.setText(strFieldName2 + "");
						holder.valueTwoText.setText(fieldValue2 + "");
					}
					if (i == 2)
					{
						// 获取字段名称
						String strFieldName3 = field.getFieldName();
						// 获取对应字段的值
						Object fieldValue3 = record.getFldVal(strFieldName3);
						holder.nameThreeText.setText(strFieldName3 + "");
						holder.valueThreeText.setText(fieldValue3 + "");
					}
				}

			}
			// 点击事件
			holder.featureDetailLayout.setOnClickListener(new OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					FeatureDetailFrag featureDetailFrag = new FeatureDetailFrag();
					Bundle data = new Bundle();
					data.putSerializable("id", position);
					data.putSerializable("feature", feature);
					featureDetailFrag.setArguments(data);
					mMapActivity.addFragment(EnumViewPos.FULL, featureDetailFrag, featureDetailFrag.getName(), null);
					mMapActivity.addFragBackListen(featureDetailFrag);
				}
			});
			holder.contentLayout.setOnClickListener(new OnClickListener()
			{
				
				@Override
				public void onClick(View v)
				{
					List<Graphic> graphicLst = feature.toGraphics(true);
					for(Graphic gra:graphicLst)
					{
						gra.setColor(Color.argb(200, 255, 0, 0));
						mMapView.getGraphicsOverlay().addGraphic(gra);
						mGraphicLst.add(gra);
						mMapView.zoomToRange(MapUtil.zoomRect(gra.getBoundingRect()), true);
//						mMapView.zoomToRange(gra.getBoundingRect(), true);
						mMapView.refresh();
					}
					graphicToCenter(position);
					
				}
			});

			return convertView;
		}

		public List<Feature> getFeatueLst()
		{
			return featureLst;
		}

		public void setFeatueLst(List<Feature> featueLst)
		{
			this.featureLst = featueLst;
		}

		class ViewHolder
		{
			public LinearLayout contentLayout;
			public TextView idText;
			public TextView oidText;
			public TextView nameOneText;
			public TextView valueOneText;
			public TextView nameTwoText;
			public TextView valueTwoText;
			public TextView nameThreeText;
			public TextView valueThreeText;
			public ImageView featureDetailImv;
			public LinearLayout featureDetailLayout;

		}

	}
	
	/**
	 * 点击将当前Graphic移动到可视范围
	 * @param id
	 */
	private void graphicToCenter(int id)
	{
		//点击将当前Graphic移动到可视范围
		Graphic gra = mGraphicLst.get(id);
		Dot graCenter = gra.getCenterPoint();
		Dot center = new Dot(graCenter.x,graCenter.y - MapUtil.pxToMapDis(mMapView, 360));
		mMapView.panToCenter(center, true);
		
	}

	@Override
	public void onDestroyView()
	{
		mMapView.setAnimationListener(null);
		mMapView.getAnnotationsOverlay().removeAllAnnotations();
		mMapView.getGraphicsOverlay().removeGraphics(mGraphicLst);
		mMapView.refresh();
		super.onDestroyView();
	}
	
	@Override
	public boolean goback()
	{
		return false;
	}

	@Override
	public boolean isLocked()
	{
		return false;
	}

	@Override
	public String getName()
	{
		return TAG;
	}

}
